package com.mulanweb.api.module.controller.wechat;

import com.jfinal.core.Controller;
import com.mulanweb.api.module.model.*;
import com.mulanweb.db.common.Constant;
import com.mulanweb.db.common.RandomStringGenerator;
import com.mulanweb.db.common.WxParaFormatter;
import com.mulanweb.utils.WxSignUtil;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.util.*;

/**
 * Created by Administrator on 2016/8/31.
 */
public class WxPayController extends Controller {



    public void startRequest() {
        Order order = Order.dao.findFirst("SELECT * FROM `order` WHERE order_number = ?",getPara("orderNumber"));
        if (order != null) {
            String title = "新西兰微助手默认订单" ;
            if(order.getTypeId() == 23){
                Ticket ticket = Ticket.dao.findById(order.getTargetId());
                title = ticket.getTitle();
            }else if(order.getTypeId() ==24){
                Chartered chartered = Chartered.dao.findById(order.getTargetId());
                title = chartered.getTitle();
            }
            int orderTotalFee = (int)((order.getAmount() * order.getUnitPrice()) * 100) ;
            if(order.getCouponId() != null ){
                Coupon coupon = Coupon.dao.findById(order.getCouponId());
                int couponValue = (int) (coupon.getValue()*100);
                orderTotalFee = orderTotalFee - couponValue;
            }

            String appid = Constant.WeChatFinalValue.APPID;//微信分配的公众账号ID（企业号corpid即为此appId）
            String mch_id = Constant.WeChatFinalValue.MCHID;//微信支付分配的商户号
            String device_info = "WEB";//设备号(终端设备号(门店号或收银设备ID)，注意：PC网页或公众号内支付请传"WEB")
            String nonce_str = RandomStringGenerator.getRandomStringByLength(32);//这是随机字符串
            String sign = null; //所有参数按一定算法得到的签名
            String body = title;//商品简单描述，该字段须严格按照规范传递，具体请见参数规定(https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=4_2)
            String out_trade_no = order.getOrderNumber();//商户系统内部的订单号,32个字符内、可包含字母, 其他说明见商户订单号(https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=4_2)
            int total_fee = orderTotalFee; //订单总金额，单位为分，详见支付金额(地址同上)
            String spbill_create_ip = "192.168.1.1";//APP和网页支付提交用户端ip，Native支付填调用微信支付API的机器IP。
            String notify_url = "http://bluefly.51vip.biz/mulan_xxl/view/menu2/ticket/list.jsp";//接收微信支付异步通知回调地址，通知url必须为直接可访问的url，不能携带参数。
            String trade_type = "JSAPI"; //JSAPI--公众号支付、NATIVE--原生扫码支付、APP--app支付，统一下单接口trade_type的传参可参考这里MICROPAY--刷卡支付，刷卡支付有单独的支付接口，不调用统一下单接口
            String openid = super.getSessionAttr("openId");
            //String openid = "oULNBwOvt_D2A_8se1bQOQ06ky0w";

            SortedMap<Object, Object> para = new TreeMap<Object, Object>();
            para.put("appid", appid);
            para.put("mch_id", mch_id);
            para.put("device_info", device_info);
            para.put("nonce_str", nonce_str);
            para.put("body", body);
            para.put("out_trade_no", out_trade_no);
            para.put("total_fee", total_fee + "");
            para.put("spbill_create_ip", spbill_create_ip);
            para.put("notify_url", notify_url);
            para.put("trade_type", trade_type);
            para.put("openid", openid);
            sign = WxSignUtil.createGetPrepayIdSign(para);
            para.put("sign", sign);
            String xml = WxParaFormatter.getRequestXml(para);

            CloseableHttpClient client = HttpClients.createDefault();
            HttpPost post = new HttpPost(Constant.WeChatFinalValue.GET_PREPAYID_URL);
            post.addHeader("Content/Type", "application/xml");
            StringEntity stringEntity = new StringEntity(xml, ContentType.create("application/xml", "UTF-8"));
            post.setEntity(stringEntity);
            CloseableHttpResponse resp = null;
            try {
                resp = client.execute(post);
            } catch (IOException e) {
                e.printStackTrace();
            }
            int returnCode = resp.getStatusLine().getStatusCode();
            String str = "";
            if (200 <= returnCode && 300 >= returnCode) {
                try {
                    str = (EntityUtils.toString(resp.getEntity()));

                    Map<String, String> result = WxParaFormatter.xmlToMap(str);
                    System.out.println(result);

                    SortedMap<Object, Object> params = new TreeMap<Object, Object>();
                    params.put("appId", appid);
                    params.put("timeStamp", Long.toString(new Date().getTime()));
                    params.put("nonceStr", result.get("nonce_str"));
                    params.put("package", "prepay_id=" + result.get("prepay_id"));
                    params.put("signType", "MD5");

                    String paySign = WxSignUtil.createGetPrepayIdSign(params);
                    params.put("packageValue", "prepay_id=" + result.get("prepay_id"));    //这里用packageValue是预防package是关键字在js获取值出错
                    params.put("paySign", paySign);                                                          //paySign的生成规则和Sign的生成规则一致
                    params.put("sendUrl", "/mulanweb/common/order/checkPayStatus?orderNumber="+out_trade_no);                               //付款成功后跳转的页面
                    String userAgent = super.getRequest().getHeader("user-agent");
                    char agent = userAgent.charAt(userAgent.indexOf("MicroMessenger") + 15);
                    renderJson("DataList", params);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (ParserConfigurationException e) {
                    e.printStackTrace();
                } catch (SAXException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void startRequestVisaOrder() {
        VisaOrder visaOrder = VisaOrder.dao.findFirst("SELECT * FROM `visa_order` WHERE order_number = ?",getPara("orderNumber"));
        if (visaOrder != null) {
           Visa visa= Visa.dao.findById(VisaChild.dao.findById(visaOrder.getVisaChildId()).getParentId());
            String title = visa.getTitle() ;
            int orderTotalFee = (int)(visaOrder.getShouldPayment() * 100) ;

            String appid = Constant.WeChatFinalValue.APPID;//微信分配的公众账号ID（企业号corpid即为此appId）
            String mch_id = Constant.WeChatFinalValue.MCHID;//微信支付分配的商户号
            String device_info = "WEB";//设备号(终端设备号(门店号或收银设备ID)，注意：PC网页或公众号内支付请传"WEB")
            String nonce_str = RandomStringGenerator.getRandomStringByLength(32);//这是随机字符串
            String sign = null; //所有参数按一定算法得到的签名
            String body = title;//商品简单描述，该字段须严格按照规范传递，具体请见参数规定(https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=4_2)
            String out_trade_no = visaOrder.getOrderNumber();//商户系统内部的订单号,32个字符内、可包含字母, 其他说明见商户订单号(https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=4_2)
            int total_fee = orderTotalFee; //订单总金额，单位为分，详见支付金额(地址同上)
            String spbill_create_ip = "192.168.1.1";//APP和网页支付提交用户端ip，Native支付填调用微信支付API的机器IP。
            String notify_url = "http://bluefly.51vip.biz/mulan_xxl/view/menu2/ticket/list.jsp";//接收微信支付异步通知回调地址，通知url必须为直接可访问的url，不能携带参数。
            String trade_type = "JSAPI"; //JSAPI--公众号支付、NATIVE--原生扫码支付、APP--app支付，统一下单接口trade_type的传参可参考这里MICROPAY--刷卡支付，刷卡支付有单独的支付接口，不调用统一下单接口
            String openid = super.getSessionAttr("openId");
            //String openid = "oULNBwOvt_D2A_8se1bQOQ06ky0w";

            SortedMap<Object, Object> para = new TreeMap<Object, Object>();
            para.put("appid", appid);
            para.put("mch_id", mch_id);
            para.put("device_info", device_info);
            para.put("nonce_str", nonce_str);
            para.put("body", body);
            para.put("out_trade_no", out_trade_no);
            para.put("total_fee", total_fee + "");
            para.put("spbill_create_ip", spbill_create_ip);
            para.put("notify_url", notify_url);
            para.put("trade_type", trade_type);
            para.put("openid", openid);
            sign = WxSignUtil.createGetPrepayIdSign(para);
            para.put("sign", sign);
            String xml = WxParaFormatter.getRequestXml(para);

            CloseableHttpClient client = HttpClients.createDefault();
            HttpPost post = new HttpPost(Constant.WeChatFinalValue.GET_PREPAYID_URL);
            post.addHeader("Content/Type", "application/xml");
            StringEntity stringEntity = new StringEntity(xml, ContentType.create("application/xml", "UTF-8"));
            post.setEntity(stringEntity);
            CloseableHttpResponse resp = null;
            try {
                resp = client.execute(post);
            } catch (IOException e) {
                e.printStackTrace();
            }
            int returnCode = resp.getStatusLine().getStatusCode();
            String str = "";
            if (200 <= returnCode && 300 >= returnCode) {
                try {
                    str = (EntityUtils.toString(resp.getEntity()));

                    Map<String, String> result = WxParaFormatter.xmlToMap(str);
                    System.out.println(result);

                    SortedMap<Object, Object> params = new TreeMap<Object, Object>();
                    params.put("appId", appid);
                    params.put("timeStamp", Long.toString(new Date().getTime()));
                    params.put("nonceStr", result.get("nonce_str"));
                    params.put("package", "prepay_id=" + result.get("prepay_id"));
                    params.put("signType", "MD5");

                    String paySign = WxSignUtil.createGetPrepayIdSign(params);
                    params.put("packageValue", "prepay_id=" + result.get("prepay_id"));    //这里用packageValue是预防package是关键字在js获取值出错
                    params.put("paySign", paySign);                                                          //paySign的生成规则和Sign的生成规则一致
                    params.put("sendUrl", "/mulanweb/common/visa_order/checkPayStatus?orderNumber="+out_trade_no);                               //付款成功后跳转的页面
                    String userAgent = super.getRequest().getHeader("user-agent");
                    char agent = userAgent.charAt(userAgent.indexOf("MicroMessenger") + 15);
                    renderJson("DataList", params);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (ParserConfigurationException e) {
                    e.printStackTrace();
                } catch (SAXException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
